
//
//  DDPictureSelectorVC.swift
//  DDPictureSelectorTest
//
//  Created by dqw on 15/8/7.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let DDCellReuseID = "DDReuseID"


class DDPictureSelectorVC: UICollectionViewController, DDPictureSelectorCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    lazy var images = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()


        configurePictureSelectorView()
     
    }
    
    func configurePictureSelectorView() {
        collectionView?.backgroundColor = UIColor.whiteColor()
        self.collectionView!.registerClass(DDPictureSelectorCell.self, forCellWithReuseIdentifier: DDCellReuseID)
    }

    
    init() {
        super.init(collectionViewLayout: DDFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return (images.count) + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DDCellReuseID, forIndexPath: indexPath) as! DDPictureSelectorCell
//        cell.backgroundColor = UIColor.lightGrayColor()
        cell.delegate = self
        cell.image = (indexPath.item < images.count) ? images[indexPath.item] : nil
   
        cell.removeButton.hidden = (indexPath.item == images.count)
        
        cell.tag = indexPath.item

        return cell
    }
    private var currentIndex = 0
    
    private func willAddPicture(pictureSelectorCell: DDPictureSelectorCell) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        
        currentIndex = (collectionView?.indexPathForCell(pictureSelectorCell)?.item)!
        
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    
    
    private func willRemovePicture(pictureSelectorCell: DDPictureSelectorCell) {
        
        images.removeAtIndex(pictureSelectorCell.tag)
        collectionView?.reloadData()
    }
    
//    var iamges: [UIImage]
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        
        let scaledImage = image.scaledImage(300)
        
        if currentIndex < images.count {
            images[currentIndex] = scaledImage
            
        }else {
            images.append(scaledImage)
        }
        
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

private protocol DDPictureSelectorCellDelegate: NSObjectProtocol {
    
     func willAddPicture(pictureSelectorCell: DDPictureSelectorCell)
     func willRemovePicture(pictureSelectorCell: DDPictureSelectorCell)
}

private class DDPictureSelectorCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configureCell()
    }
    
    weak var delegate: DDPictureSelectorCellDelegate?
    var image: UIImage? {
        
        didSet {
            if image == nil {
               addButton.setImage("compose_pic_add")
                return
            }
            
            addButton.setImage(image, forState: UIControlState.Normal)
        }
    }
    
   @objc private func addPicture() {
       delegate?.willAddPicture(self)
    }
   @objc private func removePicture() {
        delegate?.willRemovePicture(self)
    }
    
    private func configureCell() {
        addSubview(addButton)
        addSubview(removeButton)
        removeButton.hidden = true
        addButton.addTarget(self, action: "addPicture", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: UIControlEvents.TouchUpInside)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["add": addButton, "remove": removeButton]
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[add]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[add]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
    }
    
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add")
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close")
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

private class DDFlowLayout: UICollectionViewFlowLayout {
    
    private override func prepareLayout() {
        let margin:CGFloat = 10
        itemSize = CGSize(width: 80, height: 80)
        scrollDirection = UICollectionViewScrollDirection.Vertical
//        minimumInteritemSpacing = 0
//        minimumLineSpacing = 0
        sectionInset = UIEdgeInsets(top: 2 * margin, left: margin, bottom: margin, right: margin)
    }
    
    
}
